const express = require("express");
const url = require("url");
const fs = require("fs");
const mime = require("mime");
const path = require("path");
const app = express();

// 延时中间件
app.use(function (req, res, next) {
  const { pathname, query } = url.parse(req.url, true);
  const fileName = path.resolve(__dirname, "./3.render" + pathname);
  const ext = path.parse(pathname).ext;
  const mimeType = mime.getType(ext);
  if (fs.existsSync(fileName) && ext && mimeType) {
    let { delay } = query;
    if ((ext == ".css" || ext == ".js") && delay) {
      setTimeout(() => {
        next();
      }, delay - 0);
    } else {
        next();
    }
  } else {
    next();
  }
});

app.use(express.static("./3.render", {}));

app.all("*", function (req, res, next) {
  //   console.log("app all", req.url);

  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  // res.header("Content-Type", "application/json;charset=utf-8");
  if (req.method == "OPTIONS") {
    res.sendStatus(200);
  }
  next();
});
const port = 20000;
const server = app.listen(port, function () {
  console.log(`Example app listening at http://localhost:${port}`);
});
